//
//  AlertPayView.m
//  CYWFrame
//
//  Created by Macx on 2017/11/1.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "AlertPayView.h"
#import "UIView+LZCView.h"
#import "AliPayServer.h"

@interface AlertPayView () <UITextFieldDelegate>

@property (nonatomic, strong) UIView *alertview;
@property (nonatomic, assign) BOOL judge;
@property (nonatomic, strong) id userInfo;

//@property (nonatomic, strong) NSMutableArray *numArr;
@property (nonatomic, strong) UIButton *seleBtn1;
@property (nonatomic, strong) UIButton *seleBtn2;

@property (nonatomic, strong) UIButton *moenyB1;
@property (nonatomic, strong) UIButton *moenyB2;
@property (nonatomic, strong) UIButton *moenyB3;
@property (nonatomic, strong) UIButton *wayB1;
@property (nonatomic, strong) UIButton *wayB2;
@property (nonatomic, strong) NSString *wayS; // 支付方式，请求param
@property (nonatomic, strong) NSString *moneyS; // 支付金额

@property (nonatomic, strong) UIView *tfView;
@property (nonatomic, strong) UITextField *tf;

@end

@implementation AlertPayView {
    CGFloat seleW;
    CGFloat seleW2;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        //创建遮罩
        UIView *mask = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        [self addSubview:mask];
        mask.backgroundColor = [UIColor blackColor];
        mask.alpha = 0.3f;
        [mask addTarget:self action:@selector(maskClick)];
        
        //创建alert
        self.alertview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-60, 10)];
        self.alertview.layer.cornerRadius = 5;
        self.alertview.clipsToBounds = YES;
        self.alertview.backgroundColor = [UIColor whiteColor];
        [self addSubview:_alertview];
        [self exChangeOut:self.alertview dur:0.2];
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 第二次就不需要重新创建
    if (self.judge == 0) {
        
        CGFloat width = self.alertview.width;
        
        // title
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, width/2, 40)];
        [self.alertview addSubview:title];
        title.text = @"打赏";
        title.textColor = kGrayColor;
        title.font = kUHSystemFontWithSize(14);
        
        // close
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.alertview addSubview:closeBtn];
        [closeBtn setImage:[UIImage imageNamed:@"live_zhubo_close"] forState:UIControlStateNormal];
        closeBtn.frame = CGRectMake(width-40, 0, 40, 40);
        [closeBtn addTarget:self action:@selector(maskClick) forControlEvents:UIControlEventTouchUpInside];
        
        // 分割线
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, title.height, width, 1)];
        [self.alertview addSubview:line1];
        line1.backgroundColor = UISeparatedColorRGB;
        
        // 头像
        UIImageView *headPic = [[UIImageView alloc] initWithFrame:CGRectMake((width-SW(5))/2 , line1.y+10, SW(5), SW(5))];
        [self.alertview addSubview:headPic];
        headPic.layer.cornerRadius = SW(10);
        headPic.layer.masksToBounds = YES;
        headPic.contentMode = UIViewContentModeScaleAspectFill;
        [headPic sd_setImageWithURL:[NSURL URLWithString:self.userInfo[@"headPic"]] placeholderImage:[UIImage imageNamed:@"placeHolder.png"]];
        
//        self.numArr = [[NSMutableArray alloc] init];
        
        NSArray *btnArr = @[@"1元", @"5元", @"10元"];
        CGFloat btnW = (width-80)/3;
        CGFloat btnY = headPic.y+headPic.height+10;
        CGSize btnSize = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(13)];
        for (int i = 0; i < btnArr.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.alertview addSubview:btn];
            [btn setTitle:btnArr[i] forState:UIControlStateNormal];
            btn.titleLabel.font = kUHSystemFontWithSize(13);
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitleColor:UIMainColorRGB forState:UIControlStateSelected];
//            btn.frame = CGRectMake(width/3*i, line.y+11, width/4, btnSize.height);
            btn.frame = CGRectMake(20+(20+btnW)*i, btnY, btnW, btnSize.height+10);
            btn.layer.borderWidth = 1;
            btn.layer.borderColor = kGrayColor.CGColor;
            btn.layer.cornerRadius = 5;
            btn.layer.masksToBounds = YES;
            btn.tag = 500+i;
            [btn addTarget:self action:@selector(payNumAction:) forControlEvents:UIControlEventTouchUpInside];
            if (i == 0) {
                self.moenyB1 = btn;
            }
            else if (i == 1) {
                self.moenyB2 = btn;
            }
            else {
                self.moenyB3 = btn;
                btnY = btnY+btnSize.height+20;
            }
//            if (i == 2) {
//                btnY = btnY+btnSize.height+40;
//            }
//            [self.numArr addObject:btn];
            
        }
        
        UILabel *Introduction = [[UILabel alloc] init];
        [self.alertview addSubview:Introduction];
        Introduction.text = @"其他金额:";
        Introduction.textColor = [UIColor grayColor];
        Introduction.textAlignment = NSTextAlignmentCenter;
        Introduction.font = kUHSystemFontWithSize(12);
        CGSize IntroductionSize = [LZCTools textSizeWithText:Introduction.text font:Introduction.font];
        Introduction.frame = CGRectMake(20, btnY, IntroductionSize.width, IntroductionSize.height);
        
        CGFloat tfX = Introduction.width+5+Introduction.x;
        UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(tfX, 0, width-tfX-20, Introduction.height+10)];
        [self.alertview addSubview:tf];
        tf.centerY = Introduction.centerY;
        tf.placeholder = @"请输入其他金额";
        tf.font = kUHSystemFontWithSize(13);
        tf.keyboardType = UIKeyboardTypeDecimalPad;
        UIImageView *moneyIcon = [[UIImageView alloc] initWithImage:IMAGE(@"icon_dollar_sign")];
        tf.leftViewMode = UITextFieldViewModeAlways;
        tf.leftView = moneyIcon;
        tf.delegate = self;
        self.tf = tf;
        
        // tf 底线
        UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(tf.x, tf.y+tf.height, width, 1)];
        [self.alertview addSubview:line2];
        line2.backgroundColor = UISeparatedColorRGB;
        
        self.tfView  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
//        [self.alertview addSubview:self.tfView];
        self.tfView.hidden = YES;
        UIViewController *currVC = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
        [currVC.view addSubview:self.tfView];
        [self.tfView addActionWithblock:^{
            [tf resignFirstResponder];
        }];
        
        // 分割线
        UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(0, tf.y+tf.height+10, width, 1)];
        [self.alertview addSubview:line3];
        line3.backgroundColor = UISeparatedColorRGB;
        
        UILabel *intro = [[UILabel alloc] initWithFrame:CGRectMake(10, line3.y+11, width/2, btnSize.height)];
        [self.alertview addSubview:intro];
        intro.text = @"打赏方式";
        intro.textColor = kGrayColor;
        intro.font = kUHSystemFontWithSize(12);
        
        NSArray *payImgArr = @[@"pay_wechat", @"pay_alipay"];
        NSArray *paybtnArr = @[@"微信支付", @"支付宝支付"];
        btnW = (width-60)/2;
        btnY = intro.y+intro.height+10;
        for (int i = 0; i < paybtnArr.count; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.alertview addSubview:btn];
            [btn setTitle:paybtnArr[i] forState:UIControlStateNormal];
            [btn setImage:IMAGE(payImgArr[i]) forState:UIControlStateNormal];
            [btn setTitleColor:UIMainColorRGB forState:UIControlStateSelected];
            btn.layer.borderWidth = 1;
            btn.layer.borderColor = kGrayColor.CGColor;
            btn.layer.cornerRadius = 5;
            btn.layer.masksToBounds = YES;
            btn.titleLabel.font = kUHSystemFontWithSize(13);
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            btn.frame = CGRectMake(20+(20+btnW)*i, btnY, btnW, btnSize.height+15);
            btn.tag = 600+i;
            [btn addTarget:self action:@selector(payWayAction:) forControlEvents:UIControlEventTouchUpInside];
            if (i == 1) {
                btnY = btnY+btnSize.height+30;
                self.wayB2 = btn;
            }
            else
                self.wayB1 = btn;
        }
        seleW = (btnSize.height+10)/2;
        seleW2 = (btnSize.height+15)/2;
        
        for (int i = 0; i < 2; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.alertview addSubview:btn];
            [btn setImage:IMAGE(@"charge_shose") forState:UIControlStateNormal];
            btn.frame = CGRectMake(0, 0, 0, 0);
            btn.userInteractionEnabled = NO;
            btn.hidden = YES;
            if (i == 1) {
                self.seleBtn2 = btn;
            }
            else
                self.seleBtn1 = btn;
        }
        
        UIButton *signBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.alertview addSubview:signBtn];
        //        [signBtn setTitle:@"我要签到" forState:UIControlStateNormal];
        signBtn.frame = CGRectMake(10, btnY, width-20, 40);
        [signBtn addTarget:self action:@selector(signClick:) forControlEvents:UIControlEventTouchUpInside];
        signBtn.backgroundColor = kRedColor;
        [signBtn setTitle:@"我要打赏" forState:UIControlStateNormal];
        signBtn.layer.cornerRadius = signBtn.height/2;
        signBtn.layer.masksToBounds = YES;
        
        self.alertview.frame = CGRectMake(0, 0, SCREEN_WIDTH-60, signBtn.y+signBtn.height+15);
        self.alertview.center = self.center;
        
    }
    self.judge = YES;
    
}


#pragma mark ==========响应方法==========
// 弹出
-(void)exChangeOut:(UIView *)changeOutView dur:(CFTimeInterval)dur{
    
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = dur;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    [changeOutView.layer addAnimation:animation forKey:nil];
    
}
- (void)maskClick
{
    // 取消弹框
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        self.alertview = nil;
        [self removeFromSuperview];
    }];
}

- (void)signClick:(UIButton *)sender {
    NSLog(@"打赏");
    
    if (!self.moneyS) {
        [LZCTools HUDMessage:@"您尚未选择打赏金额" delay:1.5f];
        return;
    }
    if (!self.wayS) {
        [LZCTools HUDMessage:@"您尚未选择支付方式" delay:1.5f];
        return;
    }
//    if ([self.moneyS integerValue] < 100) {
//        [LZCTools HUDMessage:@"打赏金额少于1元" delay:1.5f];
//        return;
//    }
    NSString *url;
    if ([self.userInfo[@"type"] isEqualToString:@"p"]) {
        url = [NSString stringWithFormat:@"%@/%@/rewards", APIPosts, self.userInfo[@"postId"]];
    }
    else if ([self.userInfo[@"type"] isEqualToString:@"v"]) {
        url = [NSString stringWithFormat:@"%@/%@/rewards", APIArticles, self.userInfo[@"postId"]];
    }
    
    
    
    NSDictionary *param = @{@"amount":self.moneyS,
                            @"channel":self.wayS};
    
    [[NetworkTool sharedTool] requestWithName:@"打赏动态" URLString:url parameters:param method:@"POST" callBack:^(id responseObject) {
        
        [self.tf resignFirstResponder];
        [self maskClick];
        
        if ([self.wayS isEqualToString:@"wx_app"]) {
            [AliPayServer wxPay:responseObject[@"data"][@"param_obj"]];
        }
        else if ([self.wayS isEqualToString:@"ali_app"]) {
            [AliPayServer aliPay:responseObject[@"data"][@"param_str"] memo:@"打赏成功"];
        }
    }];
    
}

- (void)payNumAction:(UIButton *)sender {

    self.tf.text = @"";
    if (sender.tag == 500) {
        self.moenyB1.selected = YES;
        self.moenyB2.selected = NO;
        self.moenyB3.selected = NO;
        self.seleBtn1.hidden = NO;
        self.moenyB1.layer.borderColor = UIMainColorRGB.CGColor;
        self.moenyB2.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.moenyB3.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.seleBtn1.frame = CGRectMake(self.moenyB1.x+self.moenyB1.width-seleW, self.moenyB1.y+seleW, seleW, seleW);
        self.moneyS = @"100";
    }
    else if (sender.tag == 501) {
        self.moenyB1.selected = NO;
        self.moenyB2.selected = YES;
        self.moenyB3.selected = NO;
        self.seleBtn1.hidden = NO;
        self.moenyB2.layer.borderColor = UIMainColorRGB.CGColor;
        self.moenyB1.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.moenyB3.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.seleBtn1.frame = CGRectMake(self.moenyB2.x+self.moenyB2.width-seleW, self.moenyB2.y+seleW, seleW, seleW);
        self.moneyS = @"500";
    }
    else {
        self.moenyB1.selected = NO;
        self.moenyB2.selected = NO;
        self.moenyB3.selected = YES;
        self.seleBtn1.hidden = NO;
        self.moenyB3.layer.borderColor = UIMainColorRGB.CGColor;
        self.moenyB2.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.moenyB1.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.seleBtn1.frame = CGRectMake(self.moenyB3.x+self.moenyB3.width-seleW, self.moenyB3.y+seleW, seleW, seleW);
        self.moneyS = @"1000";
    }
    
}
- (void)payWayAction:(UIButton *)sender {
    if (sender.tag == 600) {
        self.wayB1.selected = YES;
        self.wayB2.selected = NO;
        self.seleBtn2.hidden = NO;
        self.wayB1.layer.borderColor = UIMainColorRGB.CGColor;
        self.wayB2.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.seleBtn2.frame = CGRectMake(self.wayB1.x+self.wayB1.width-seleW2, self.wayB1.y+seleW2, seleW2, seleW2);
        self.wayS = @"wx_app";
    }
    else {
        self.wayB1.selected = NO;
        self.wayB2.selected = YES;
        self.seleBtn2.hidden = NO;
        self.wayB2.layer.borderColor = UIMainColorRGB.CGColor;
        self.wayB1.layer.borderColor = UISeparatedColorRGB.CGColor;
        self.seleBtn2.frame = CGRectMake(self.wayB2.x+self.wayB2.width-seleW2, self.wayB2.y+seleW2, seleW2, seleW2);
        self.wayS = @"ali_app";
    }
}

// tf 代理
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.moenyB1.selected = NO;
    self.moenyB2.selected = NO;
    self.moenyB3.selected = NO;
    self.moenyB3.layer.borderColor = UISeparatedColorRGB.CGColor;
    self.moenyB2.layer.borderColor = UISeparatedColorRGB.CGColor;
    self.moenyB1.layer.borderColor = UISeparatedColorRGB.CGColor;
    self.seleBtn1.hidden = YES;
    self.moneyS = @"0";
    self.tfView.hidden = NO;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([self.userInfo[@"type"] isEqualToString:@"v"]) {
        self.moneyS = [NSString stringWithFormat:@"%lf", [textField.text floatValue]];
    }
    else if ([self.userInfo[@"type"] isEqualToString:@"p"]) {
        self.moneyS = [NSString stringWithFormat:@"%lf", [textField.text floatValue]*100];
    }
    NSLog(@"end");
    self.tfView.hidden = YES;
}

- (void)initShow:(id)userInfo {
    NSLog(@"可以弹出alert");
    self.userInfo = userInfo;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
